<template>
  <div v-if="visible"
       class='publish-container'>
    <el-dialog :visible.sync="visible"
               title="发布应用"
               :close-on-click-modal="false"
               @close="dialogClose">
      <el-form :model="editAppForm"
               :rules="formRules"
               ref="appForm"
               label-width="110px">
        <el-form-item label="应用名称"
                      prop="app_name">
          <el-input v-model="editAppForm.app_name"
                    placeholder="请输入应用名称">
          </el-input>
        </el-form-item>
        <el-form-item label="应用描述"
                      prop="app_des">
          <el-input v-model="editAppForm.app_des"
                    placeholder="请输入应用描述"
                    type="textarea">
          </el-input>
        </el-form-item>
        <el-form-item label="菜单分组"
                      prop="app_menu">
          <el-select v-model="editAppForm.app_menu"
                     placeholder="请选择菜单分组">
            <el-option v-for="item in appMenuCode"
                       :key="item.code_id"
                       :label="item.name"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用分组"
                      prop="app_group">
          <el-select v-model="editAppForm.app_group"
                     placeholder="请选择应用分组">
            <el-option v-for="item in appGroupCode"
                       :key="item.code_id"
                       :label="item.name"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务领域类别"
                      prop="business_field">
          <el-select v-model="editAppForm.business_field"
                     style="display:block!important"
                     multiple
                     placeholder="请选择业务领域">
            <el-option v-for="item in businessArea"
                       :key="item.value"
                       :label="item.name"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理职能类别"
                      prop="manage_function">
          <el-select v-model="editAppForm.manage_function"
                     style="display:block!important"
                     multiple
                     placeholder="请选择管理职能">
            <el-option v-for="item in manageFunction"
                       :key="item.value"
                       :label="item.name"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布端口"
                      prop="publish_target_list">
          <el-checkbox-group v-model="editAppForm.publish_target_list">
            <el-checkbox label="intecons">哈比丁智慧工地小程序</el-checkbox>
            <el-checkbox label="score">哈比丁劳务通小程序</el-checkbox>
            <el-checkbox label="ydt">工地一点通</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="工地一点通logo"
                      prop="ydt_logo">
          <el-upload class="avatar-uploader"
                     action=""
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload"
                     :http-request="uploadProjectImg">
            <img v-if="editAppForm.ydt_logo"
                 :src="editAppForm.ydt_logo"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button @click="editApp"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { CommonCheckApi } from '@/services/SystemSetting'
import { permissionApi } from '@/services/CompanySetting'
import { standardCodeApi } from '@/services/StandardCode'
import { UploadFileApi } from '@/services/UserPermission'
export default {
  data () {
    return {
      visible: false,
      editAppForm: {
        app_name: '',
        app_des: '',
        app_menu: '',
        app_group: '',
        app_endpoint: '2',
        ascription: '1',
        ascription_company_id: '',
        app_url: '',
        logo: '',
        app_source: '1',
        source_id: '',
        screenshots: '',
        is_publish: '1',
        is_auth: '1',
        publish_target_list: [],
        publish_target: '',
        ydt_logo: ''
      },
      formRules: {
        app_name: [
          { required: true, message: '请输入应用名称', trigger: 'blur' }
        ],
        app_des: [
          { required: true, message: '请输入应用描述', trigger: 'blur' }
        ],
        publish_target_list: [
          { required: true, message: '请选择发布端口', trigger: 'blur' }
        ],
        app_menu: [
          { required: true, message: '请选择菜单分组', trigger: 'blur' }
        ]
      },
      resetForm: {
        app_name: '',
        app_des: '',
        app_menu: '',
        app_group: '',
        app_endpoint: '2',
        ascription: '1',
        ascription_company_id: '',
        app_url: '',
        logo: '',
        app_source: '1',
        source_id: '',
        screenshots: '',
        is_publish: '1',
        is_auth: '1',
        publish_target: '',
        publish_target_list: [],
        ydt_logo: ''
      },
      // 应用分组标准码
      appGroupCode: [],
      appGroupMap: new Map(),
      // 菜单分组标准码
      appMenuCode: [],
      appMenuMap: new Map(),
      business_field: [],
      manage_function: [],
    }
  },
  props: {
    dialogVisible: {
      type: Boolean
    },
    dialogStatus: {
      type: String,
      default: "create"
    },
    dialogForm: {
      type: Object
    },
    callback: {
      type: Function
    },
    // 业务类型，区分监控台业务及检查项业务
    businessType: {
      type: String,
      default: 'check'
    }
  },
  watch: {
    dialogVisible (newval) {
      this.visible = newval;
    },
    dialogForm: {
      async handler (newval, oldval) {

        let temp = JSON.parse(JSON.stringify(newval));
        let reset = JSON.parse(JSON.stringify(this.resetForm))
        this.editAppForm = Object.assign(reset, temp)
        await this.getAppDetail()
        this.editAppForm.logo = temp.logo
        this.editAppForm.app_name = this.editAppForm.app_name || this.editAppForm.tpl_name
        this.editAppForm.app_des = this.editAppForm.app_des || this.editAppForm.tpl_name
        console.log(this.editAppForm, temp, '123')
      },
      deep: true
    }
  },
  methods: {
    // 图片上传功能
    handleAvatarSuccess (res, file) {

    },
    // 图片上传前的钩子
    beforeAvatarUpload (file) {

    },
    // 上传logo图片
    uploadProjectImg (file) {
      let formData = new FormData()
      formData.append('module', 'industry')
      formData.append('pic_file_apk', file.file)
      UploadFileApi.uploadFile({
        data: formData
      }).then(res => {
        if (res.data) {
          this.$message.success('上传成功')
          this.editAppForm.ydt_logo = res.data.file_path;//全路径          
        }
      })
    },
    dialogClose () {
      // this.$refs.appForm.resetFields();
      this.$emit("update:dialogVisible", false);
    },
    // 获取应用详情
    getAppDetail () {
      return permissionApi.getAppDetail({
        params: {
          app_source: '1',
          source_id: this.editAppForm._id
        }
      }).then(res => {
        if (res.code === 0) {
          if (res.data.list.length > 0) {
            let data = res.data.list[0]
            this.editAppForm = Object.assign(this.editAppForm, data)
            this.editAppForm.publish_target_list = this.editAppForm.publish_target.split(',')
            this.editAppForm.business_field = this.editAppForm.business_field === null ? [] : this.editAppForm.business_field.split(',') || []
            this.editAppForm.manage_function = this.editAppForm.manage_function === null ? [] : this.editAppForm.manage_function.split(',') || []
          } else {

          }
        }
      })
    },
    editApp () {
      this.$refs.appForm.validate((valid) => {
        if (valid) {
          this.editAppForm.publish_target = this.editAppForm.publish_target_list.join(',')
          this.editAppForm.business_field = this.editAppForm.business_field.join(',')
          this.editAppForm.manage_function = this.editAppForm.manage_function.join(',')
          if (this.editAppForm.app_no) {
            this.updateApp()
          } else {
            this.publishApp()
          }

        }
      })
    },
    // 修改app
    updateApp () {
      this.editAppForm.id = this.editAppForm.app_id
      if (this.businessType === 'monitor') {
        this.editAppForm.app_sort = '2'
      }
      permissionApi.updateApp({
        data: this.editAppForm
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('修改应用成功')
          this.$emit('callback', '')
          this.dialogClose()
        }
      })
    },
    // 发布app
    publishApp () {
      let userInfo = window.localStorage.getItem('userInfo') || '{}'
      userInfo = JSON.parse(userInfo)
      this.editAppForm.ascription_company_id = userInfo.comp_id
      this.editAppForm.source_id = this.editAppForm._id
      if (this.businessType === 'monitor') {
        this.editAppForm.app_sort = '2'
      }
      permissionApi.publishApp({
        data: this.editAppForm
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('发布应用成功')
          this.$emit('callback', '')
          this.dialogClose()
        }
      })
    },
    // 获取应用分组标准码
    getAppGroupCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'applicationGroup',

        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.appGroupCode = res.data.list
          window.localStorage.setItem('appGroupCodeLocal', JSON.stringify(this.appGroupCode))
          this.convertCodeListToMap(this.appGroupMap, this.appGroupCode)
        }
      })
    },
    // 将标准码列表转换为map
    convertCodeListToMap (map, codeList) {
      codeList.map((item) => {
        map.set(item.value, item)
      })
    },
    // 获取菜单分组标准码
    getAppMenuCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'applicationMenu'
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.appMenuCode = res.data.list
          window.localStorage.setItem('appMenuCodeLocal', JSON.stringify(this.appMenuCode))
          this.convertCodeListToMap(this.appMenuMap, this.appMenuCode)
        }
      })
    },
    //管理职能选择框
    changManage (val) {
      this.editAppForm.manage_function = val
    },
    //业务领域选择框
    changBusiness (val) {
      this.editAppForm.business_field = val
    },
    // 获取业务领域标准码
    getbusinessCode () {
      standardCodeApi.getStandardCode({
        params: {
          code_type: 'businessField',
          is_page: 0
        }
      }).then((res) => {
        this.businessArea = res.data.list
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取管理职能标准码
    getmanageCode () {
      standardCodeApi.getStandardCode({
        params: {
          code_type: 'manageFunction',
          is_page: 0
        }
      }).then((res) => {
        this.manageFunction = res.data.list
      }).catch((error) => {
        console.log(error)
      })
    },
  },
  async created () {
    let appGroupCodeLocal = window.localStorage.getItem('appGroupCodeLocal')
    let appMenuCodeLocal = window.localStorage.getItem('appMenuCodeLocal')
    if (appGroupCodeLocal) {
      this.appGroupCode = JSON.parse(appGroupCodeLocal)
      this.convertCodeListToMap(this.appGroupMap, this.appGroupCode)
    } else {
      await this.getAppGroupCode()
    }
    if (appMenuCodeLocal) {
      this.appMenuCode = JSON.parse(appMenuCodeLocal)
      this.convertCodeListToMap(this.appMenuMap, this.appMenuCode)
    } else {
      await this.getAppMenuCode()
    }
    this.getbusinessCode()
    this.getmanageCode()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.publish-container {
  .el-select {
    width: 100%;
  }
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>